package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.bean.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class CartController {


    @Autowired
    CartService cartService;

    /*
    添加购物车
     */
    @GetMapping
    public String addCart(Cart cart){
        cartService.addCart(cart);
        return "redirect:http://cart.gmall.com/addCart.html?skuId="+cart.getSkuId()+ "&count=" + cart.getCount();
    }

    /*
    根据用户id获取购物车中的商品信息
     */
    @GetMapping("{userId}")
    @ResponseBody
    public ResponseVo<List<Cart>> queryCartByUserId(@PathVariable("userId")Long userId){
        List<Cart> carts = cartService.queryCartByUserId(userId);
        return ResponseVo.ok(carts);
    }
    /*
    跳转到添加购物车成功页面
     */
    @GetMapping("addCart.html")
    public String toCart(Cart cart, Model model){
        Cart redisCart = cartService.queryAddCart(cart);
        redisCart.setCount(cart.getCount());
        model.addAttribute("cart",redisCart);
        return "addCart";
    }

    /*
    查询购物车
     */
    @GetMapping("cart.html")
    public String queryCart(Model model){
        List<Cart> carts = cartService.queryCart();
        model.addAttribute("carts",carts);
        return "cart";
    }

    /*
    选择购物车中的商品
     */
    @PostMapping("updateNum")
    @ResponseBody
    public ResponseVo updateNum(@RequestBody Cart cart){
        cartService.updateNum(cart);
        return ResponseVo.ok();
    }

}
